﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using Runda.EShop.Common.Entity;

namespace Runda.EShop.Dal
{
    public partial class SysFunctionDal
    {
        /// <summary>
        /// 根据角色构造功能点树
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public DataTable BuildAllFunction(Guid RoleID)
        {
            string sql = @"select A.*, 
case when B.RoleID IS NULL then 0 else 1 end as IsChecked
from Sys_Function A
left join Sys_RoleFunctionRelation B ON A.FuncID = B.FuncID and B.RoleID =@RoleID
";
            DbCommand dbcommand = CurrentDatabase.GetSqlStringCommand(sql);
            CurrentDatabase.AddInParameter(dbcommand, "@RoleID", DbType.Guid, RoleID);

            return CurrentDatabase.ExecuteDataSet(dbcommand).Tables[0];
        }

        public DataTable LoadAllFunctionWithPath()
        {
            string sql = @"with cte as
(
select *
,cast('首页 - '+FuncName as varchar(max)) as Location 
from [Sys_Function] where FFuncID is null
union all
select a.*
,cast(b.Location+' - '+a.FuncName as varchar(max)) as Location 
from Sys_Function a join cte b on a.FFuncID = b.FuncID
)
select * from cte";

            DbCommand dbcommand = CurrentDatabase.GetSqlStringCommand(sql);
            return CurrentDatabase.ExecuteDataSet(dbcommand).Tables[0];
        }

        public DataTable LoadUserAllFunction()
        {
            string sql = @"select C.*,B.UserID from Sys_RoleFunctionRelation A join Sys_UserRoleRelation B on
A.RoleID = B.RoleID 
join Sys_Function C on A.FuncID = C.FuncID
ORDER BY A.FuncID
";
            DbCommand dbcommand = CurrentDatabase.GetSqlStringCommand(sql);
            return CurrentDatabase.ExecuteDataSet(dbcommand).Tables[0];
        }

        /// <summary>
        /// 获取用户具有的权限
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List<SysFunctionEntity> LoadUserHavedFunction(Guid UserID)
        {
            List<SysFunctionEntity> entities = new List<SysFunctionEntity>();
            string sql = @"select C.* from Sys_RoleFunctionRelation A join Sys_UserRoleRelation B on
A.RoleID = B.RoleID 
join Sys_Function C on A.FuncID = C.FuncID
where B.UserID = @UserID";
            DbCommand dbcommand = CurrentDatabase.GetSqlStringCommand(sql);
            CurrentDatabase.AddInParameter(dbcommand, "@UserID", DbType.Guid, UserID);

            using (IDataReader reader = CurrentDatabase.ExecuteReader(dbcommand))
            {
                entities = base.GetListFromReader<SysFunctionEntity>(reader);
            }

            return entities;
        }
    }
}
